package com.syqc.monitor.download

import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.Buffer
import okio.BufferedSource
import okio.ForwardingSource
import okio.Source
import okio.buffer

/**
 *@Author pc_hfjs
 *@Date 2022/3/19 15:16
 *@Desc
 */
class FileResponseBody(
    private val responseBody: ResponseBody,
    private val callback: DownCallback
) : ResponseBody() {

    private var bufferSource: BufferedSource? = null

    override fun contentLength(): Long {
        return responseBody.contentLength()
    }

    override fun contentType(): MediaType? {
        return responseBody.contentType()
    }

    override fun source(): BufferedSource {
        if (bufferSource == null) {
            bufferSource = getSource(responseBody.source()).buffer()
        }
        return bufferSource!!
    }


    private fun getSource(source: Source): Source {
        return object : ForwardingSource(source) {
            var bytesSize = 0L
            override fun read(sink: Buffer, byteCount: Long): Long {
                val bytesLength = super.read(sink, byteCount)
                bytesSize += (if (bytesLength.toInt() != -1) bytesLength else 0)
                callback.onLoading(responseBody.contentLength(), bytesSize)
                return bytesLength
            }
        }
    }
}